<?php

namespace Yunshop\VirtualCardTeam\admin;

use app\common\components\BaseController;
use app\common\models\Coupon;
use app\common\models\Goods;
use app\common\models\Order;
use app\common\models\OrderGoods;
use Yunshop\TeamDividend\models\TeamDividendAgencyModel;
use Yunshop\VirtualCard\model\VirtualData;
use Yunshop\VirtualCard\model\VirtualOrder;
use Yunshop\VirtualCardTeam\common\models\Activity;
use Yunshop\VirtualCardTeam\common\models\ExpectCard;
use Yunshop\VirtualCardTeam\common\models\GiveLog;


class CardController extends BaseController
{
    public function index()
    {
        return view('Yunshop\VirtualCardTeam::card.list')->render();
    }

    public function getData()
    {
        $list = ExpectCard::uniacid()->search(request()->search)
            ->orderBy('id', 'desc')
            ->paginate();
        return $this->successJson('ok', $list);
    }

    public function detail()
    {
        if (request()->ajax()) {
            $expect_card_id = request()->id;
            $expect_card = ExpectCard::uniacid()->find($expect_card_id);
            $list = GiveLog::uniacid()
                ->with(['hasVirtualData'])
                ->where('order_id', $expect_card->order_id)
                ->get()
                ->toArray();
            return $this->successJson('ok', [
                'data' => $list,
            ]);
        }
        return view('Yunshop\VirtualCardTeam::card.grant_list')->render();
    }


    public function addCard()
    {
        $order_id = request()->order_id;
        $card_num = request()->card_num;
        $add_type = request()->add_type;
        if ($add_type == 2) {
            $expect_card =  ExpectCard::uniacid()->where('order_id', $order_id)->first();
            if (!$expect_card) {
                return $this->errorJson('该订单没有预计卡密');
            }
            $expect_card->card_num = $card_num;
            $expect_card->save();
            return $this->successJson('修改成功');
        }
        $order = Order::uniacid()->find($order_id);
        $agent = TeamDividendAgencyModel::uniacid()->where('uid', $order->uid)->first();

        if (!$agent) {
            return $this->errorJson('该订单所属会员不是经销商');
        }
        $expect_card = ExpectCard::uniacid()->where('member_id', $order->uid)->first();
        if ($expect_card) {
            return $this->errorJson('该会员已有预计卡密');
        }
        $set = \Setting::get('plugin.virtual-card-team');

        if (!$set['virtual_card_type_id']) {
            return $this->errorJson('请先设置卡密类型');
        }
        $order_goods = OrderGoods::uniacid()->where('order_id', $order_id)->first();
        $data = [
            'uniacid' => \YunShop::app()->uniacid,
            'goods_id' => $order_goods->goods_id,
            'order_id' => $order_id,
            'card_type_id' => $set['virtual_card_type_id'],
            'card_num' => $card_num,
            'card_num_give' => 0,
            'member_id' => $order->uid,
        ];
        try {
            ExpectCard::create($data);
            return $this->successJson('添加成功');
        } catch (\Exception $e) {
            return $this->errorJson($e->getMessage());
        }
    }

    public function send()
    {
        $id = request()->id;
        $give_num = 1;
        $set  = \Setting::get('plugin.virtual-card-team');
        $expect_card = ExpectCard::uniacid()->find($id);
        if (!$expect_card || $expect_card->card_num <= $expect_card->card_num_give) {
            return $this->errorJson('该预计卡密已发完');
        }

        if ($expect_card->card_num < $expect_card->card_num_give + $give_num) {
            $give_num = $expect_card->card_num - $expect_card->card_num_give;
        }

        $expect_card->card_num_give += $give_num;
        $virtual_order = VirtualOrder::uniacid()->first();
        if (!$virtual_order) {
            $virtual_order = new VirtualOrder();
        }

        $agent_order = Order::uniacid()->find($expect_card->order_id);
        if (!$agent_order) {
            return $this->errorJson('该订单不存在');
        }
        $virtual_order_data = [
            'uniacid' => \YunShop::app()->uniacid,
            'order_id' => $agent_order->id,
            'member_id' => $agent_order->uid,
            'order_sn' => $agent_order->order_sn,
            'order_price' => $agent_order->price,
            'status' => 1,
        ];
        $virtual_order->fill($virtual_order_data);

        $virtual_data = VirtualData::uniacid()->where('type_id', $set['virtual_card_type_id'])
            ->where('order_id', 0)
            ->where('owner_id', 0)
            ->where('status', 0)
            ->get()
            ->toArray();
        $virtual_data_num = count($virtual_data);
        if (!$virtual_data_num) {

            return $this->errorJson('该类型没有卡密数据');
        }
        if ($give_num > $virtual_data_num) {
            $give_num = $virtual_data_num;
        }
        $datas = VirtualData::getSongData($set['virtual_card_type_id'], $give_num)->get();

        //该类型没有设置卡密数据
        if ($datas->isEmpty()) {
            return $this->errorJson('该类型没有设置卡密数据');
        }
        $save_data = [
            'order_id' => $agent_order->id,
            'owner_id' => $agent_order->uid,
            'status' => 1,
        ];


        try {
            \DB::beginTransaction();
            $log = [];
            foreach ($datas as $card_data) {
                $save_data['usetime'] = time();

                $card_data->fill($save_data);

                $card_data->save();
                $log[] = [
                    'uniacid' => \YunShop::app()->uniacid,
                    'member_id' => $agent_order->uid,
                    'virtual_data_id' => $card_data->id,
                    'order_id' => $agent_order->id,
                    'type' => 2,
                    'created_at' => time(),
                    'updated_at' => time(),
                ];
            }
            $virtual_order->save();
            $expect_card->save();
            GiveLog::insert($log);
            \DB::commit();
            return $this->successJson('发放失败');
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->errorJson('发放失败');
        }
    }

}